package org.mayanjun.code.dalint.mybatis;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.mayanjun.code.dalint.Sharding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * ThreadLocalDataBaseRouter
 *
 * @author mayanjun(6/24/16)
 */
public class ThreadLocalDataBaseRouter implements DataBaseRouter, InitializingBean {

    public static final String MASTER_DATABASE = "master";
    private static final Logger LOG = LoggerFactory.getLogger(ThreadLocalDataBaseRouter.class);
    private Map<String, SqlSession> sqlSessionMap;

    private ThreadLocal<String> dataBaseThreadLocal;

    private SqlSession masterSqlSession;

    public ThreadLocalDataBaseRouter() {
        this.dataBaseThreadLocal = new ThreadLocal<String>();
    }

    @Override
    public SqlSession getDataBaseSqlSession() {
        String dataBase = getUsingDataBase();
        return sqlSessionMap.get(dataBase);
    }

    @Override
    public SqlSession getMasterDataBaseSqlSession() {
        return masterSqlSession;
    }

    @Override
    public SqlSession getDataBaseSqlSession(Sharding sharding, Object source) {
        if(sharding == null) {
            String database = getUsingDataBase();
            SqlSession session = sqlSessionMap.get(database);
            if(session == null) return masterSqlSession;
            return session;
        }
        String dataBaseName = sharding.getDataBaseName(source);
        if(StringUtils.isNotBlank(dataBaseName) && sqlSessionMap.containsKey(dataBaseName)) {
            return sqlSessionMap.get(dataBaseName);
        } else {
            if(LOG.isDebugEnabled()) {
                LOG.debug("(getDataBaseSqlSession)No database found: name='" + dataBaseName + ",' the master will be used");
            }
        }
        return masterSqlSession;
    }

    @Override
    public String getUsingDataBase() {
        return dataBaseThreadLocal.get();
    }

    @Override
    public void useDataBase(String dataBaseName) {
        if(StringUtils.isNotBlank(dataBaseName) && sqlSessionMap.containsKey(dataBaseName)) {
            dataBaseThreadLocal.set(dataBaseName);
            return;
        } else {
            if(LOG.isDebugEnabled()) {
                LOG.debug("(useDataBase)No database found: name='" + dataBaseName + "', the master will be used");
            }
        }
        dataBaseThreadLocal.set(MASTER_DATABASE);
    }

    @Required
    public void setSqlSessionMap(Map<String, SqlSession> sqlSessionMap) {
        Assert.isTrue(sqlSessionMap != null && !sqlSessionMap.isEmpty(), "sqlSessionMap can not be empty");
        this.sqlSessionMap = sqlSessionMap;
    }

    @Required
    public void setMasterSqlSession(SqlSession masterSqlSession) {
        Assert.notNull(masterSqlSession, "The master sql session must be set");
        this.masterSqlSession = masterSqlSession;
        sqlSessionMap.put(MASTER_DATABASE, masterSqlSession);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.isTrue(masterSqlSession == sqlSessionMap.get(MASTER_DATABASE), "The sqlSession named '" + MASTER_DATABASE + "' and the masterSqlSession must are the same");
        dataBaseThreadLocal.set(MASTER_DATABASE);
    }
}
